package com.flushbonading.classsystem.controller;

import com.flushbonading.classsystem.constants.StateMsg;
import com.flushbonading.classsystem.entity.CommonResult;
import com.flushbonading.classsystem.entity.User;
import com.flushbonading.classsystem.entity.vo.LoginVO;
import com.flushbonading.classsystem.service.ConfigService;
import com.flushbonading.classsystem.service.UserService;
import com.flushbonading.classsystem.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * @author zyx 2134208960@qq.com
 * @date 2021/11/8 17:00
 * @since 1.0.0
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ConfigService configService;

    @GetMapping("/getUser/userId")
    public CommonResult<User> getUserByUserId(String userId){
        if (userId==null || userId.length()<=0) {
            return CommonResult.error(StateMsg.PARAMS_ERROR);
        }
        User user = userService.getUserByUserId(userId);
        if (user==null) {
            return CommonResult.error(StateMsg.USER_NOT_FOUND);
        }
        return CommonResult.success(user);
    }

    @PostMapping("/create")
    public CommonResult createUser(@RequestBody Map<String, Object> params){
        //没有携带参数，报参数错误
        if (params.isEmpty()){
            return CommonResult.error(StateMsg.PARAMS_ERROR);
        }
        return userService.insertUser(params);
    }

    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginVO loginVO, HttpServletResponse response) {
        CommonResult loginResult = userService.login(loginVO);
        //登录成功则在响应中放入token
        if (loginResult.getStatus()==200) {
            String token = null;
            try {
                token = JWTUtil.sign(loginVO.getUserId(), loginVO.getPassword());
            } catch (UnsupportedEncodingException e) {
                //e.printStackTrace();
                log.error("生成token出错");
            }
            response.addHeader("token",token);
        }
        return loginResult;
    }
}
